import { AppThunk } from '@/store'
import { setUser, setEditUser, marge } from '../modules/profile'
import request from '@/utils/request'
import { UserPhotoResponse, UserProfile } from '@/types/data'

// 3. 异步action
export const getuser = (payload?: unknown): AppThunk => {
  return async (dispatch, getState) => {
    const res = await request.get('/user')
    // console.log(setUser(res.data))
    dispatch(setUser(res.data))
  }
}
// 3. 异步action
export const edituser = (payload?: unknown): AppThunk => {
  return async (dispatch, getState) => {
    const res = await request.get('/user/profile')
    // console.log(setUser(res.data))
    dispatch(setEditUser(res.data))
  }
}
// 3. 异步action
export const edituserInfo = (data: Partial<UserProfile>): AppThunk => {
  return async (dispatch, getState) => {
    await request.patch('/user/profile', data)
    // console.log(setUser(res.data))
    dispatch(marge(data))
  }
}
export function uploadPhotoAction(fm: FormData): AppThunk {
  return async (dispatch, getState) => {
    // 1. 把头像上传保存到服务器，返回头像的地址
    const res: UserPhotoResponse = await request.patch('/user/photo', fm)
    // dispatch()
    console.log('头像：', res.data)
    // 2. 存储头像
    dispatch(marge({ photo: res.data.photo }))
  }
}